package com.dianrui.qiyouriding.activity;


import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.content.ContextCompat;
import android.view.MotionEvent;
import android.view.View;
import android.view.Window;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.ImageView;
import com.dianrui.qiyouriding.R;
import com.dianrui.qiyouriding.adapter.SecretProtocolAdapter;
import com.dianrui.qiyouriding.dialog.LoadingDialog;
import com.dianrui.qiyouriding.event.RfreshUnread;
import com.dianrui.qiyouriding.util.ActivityManagerUtils;
import com.dianrui.qiyouriding.util.GlideUtil;
import com.dianrui.qiyouriding.util.MyUtil;
import com.dianrui.qiyouriding.util.NoDoubleClickUtils;
import com.dianrui.qiyouriding.util.ToastUtil;
import com.dianrui.qiyouriding.view.Immersion.Eyes;
import com.tbit.tbitblesdk.Bike.TbitBle;

import org.greenrobot.eventbus.EventBus;
import java.lang.ref.WeakReference;
import java.util.ArrayList;
import java.util.List;

import butterknife.ButterKnife;

public abstract class BaseActivity extends SwipeBackActivity {
    private List<ImageView> imageViewList = new ArrayList<>();
    private List<String> permissions;
    public WeakReference<BaseActivity> weakReferenceActivity;
    public WeakReference<Context> weakReferenceContext;
    private LoadingDialog mLoadingDialog;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        supportRequestWindowFeature(Window.FEATURE_NO_TITLE);//去除标题栏
        super.onCreate(savedInstanceState);
        setContentView(getContentViewId());
        weakReferenceActivity = new WeakReference<>(this);
        weakReferenceContext=new WeakReference<Context>(this);
        ButterKnife.bind(this);
        TbitBle.initialize(BaseActivity.this, new SecretProtocolAdapter());
        ActivityManagerUtils.getInstance().addActivity(this);
        initView();
    }


    @Override
    protected void onStop() {
        super.onStop();
        if (MyUtil.isAppIsInBackground(this)) {
            EventBus.getDefault().post(new RfreshUnread());
        }
    }

    /**
     * 点击控件防止多次跳转以及解决点击输入框之外的地方,让软键盘消失,并取消editText的焦点
     *
     * @param ev
     * @return
     */
    @Override
    public boolean dispatchTouchEvent(MotionEvent ev) {
        if (ev.getAction() == MotionEvent.ACTION_DOWN) {
            if (NoDoubleClickUtils.isDoubleClick()) {
                return true;
            }
            View v = getCurrentFocus();
            if (isShouldHideInput(v, ev)) {
                InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
                if (imm != null) {
                    imm.hideSoftInputFromWindow(v.getWindowToken(), 0);
                }
            }
        }
        return super.dispatchTouchEvent(ev);
    }


    public boolean isShouldHideInput(View v, MotionEvent event) {
        if (v != null && (v instanceof EditText)) {
            int[] leftTop = {0, 0};
            //获取输入框当前的location位置
            v.getLocationInWindow(leftTop);
            int left = leftTop[0];
            int top = leftTop[1];
            int bottom = top + v.getHeight();
            int right = left + v.getWidth();
            if (event.getX() > left && event.getX() < right
                    && event.getY() > top && event.getY() < bottom) {
                // 点击的是输入框区域，保留点击EditText的事件
                return false;
            } else {
                v.clearFocus();
                return true;
            }
        }
        return false;
    }


    public void showLoadingDialog(String msg) {
        mLoadingDialog= new LoadingDialog(this).setMessage(msg);
        mLoadingDialog.show();
    }

    public void dismissLoadingDialog() {
        if (mLoadingDialog != null) {
            mLoadingDialog.dismiss();
        }
    }

    public BaseActivity getBaseActivity() {
        if (weakReferenceActivity != null) {
            return weakReferenceActivity.get();
        }
        return null;
    }

    public  Context getBaseActivityContext() {
        if (weakReferenceContext != null) {
            return weakReferenceContext.get();
        }
        return null;
    }



    @Override
    protected void onPause() {
        super.onPause();
        if (MyUtil.isAppIsInBackground(this)) {
            EventBus.getDefault().post(new RfreshUnread());
        }
    }

    protected void JumpActivitys(Class<?> clazz) {
        Intent intent = new Intent(this, clazz);
        startActivity(intent);
    }

    protected void JumpKillActivitys(Class<?> clazz) {
        Intent intent = new Intent(this, clazz);
        startActivity(intent);
        finish();
    }

    public void customInit(boolean isSwipeBack, int statusColor) {//自定义初始化方法，1.是否滑动返回，2.指定沉浸式颜色
        setSwipeBackEnable(isSwipeBack);
        if (-1 != statusColor) {
            Eyes.setStatusBarLightMode(BaseActivity.this, ContextCompat.getColor(getBaseContext(), statusColor));
        }
    }

    public abstract int getContentViewId();

    public abstract void initView();

    public abstract void initData();



    class NetWorkStateReceiver extends BroadcastReceiver {
        @Override
        public void onReceive(final Context context, Intent intent) {
            if (!MyUtil.isNetworkAvalible(context)) {
                ToastUtil.showToast(getString(R.string.net_error));
            } else {
                initData();

            }
        }
    }

    /**
     * 保存图片引用
     *
     * @param imageView
     */
    public void addImageViewList(ImageView imageView) {
        if (imageViewList != null) {
            imageViewList.add(imageView);
        }
    }


    /**
     * 清除图片引用
     */
    public void clearImageViewList() {
        if (imageViewList != null) {
            for (int i = 0; i < imageViewList.size(); i++) {
                if (imageViewList.get(i) != null) {
                    GlideUtil.clearImg(this,imageViewList.get(i));
                    imageViewList.set(i, null);
                }
            }
            if (imageViewList != null) {
                imageViewList.clear();
            }
            imageViewList = null;
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (weakReferenceContext!=null){
            weakReferenceContext.clear();
        }
        if (weakReferenceActivity != null) {
            weakReferenceActivity.clear();
        }
        clearImageViewList();
        dismissLoadingDialog();
        ActivityManagerUtils.getInstance().finishActivity(this);

    }
}
